<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title>签名</title>
	</head>

	<body>
		<canvas id="canvas" style="border: 1px solid red;"></canvas>
		<div id="">
			<input type="button" id="clear" value="清空canvas"/>
		</div>
		<script type="text/javascript">
			window.onload = function() {

				var canvas = document.getElementById("canvas");
				var cxt = canvas.getContext("2d");
				canvas.width = 550;
				canvas.height = 400;
				canvasx = canvas.getBoundingClientRect().left //返回canvas距离左边的距离
				canvasy = canvas.getBoundingClientRect().top //返回canvas距离上边的距离

				//设定画线起点和终点坐标
				var startx;
				var starty;
				var endx;
				var endy;
				onoff = false; //设置画笔开关
				cxt.lineWidth = 3; //定义线段宽度

				canvas.addEventListener("mousedown", downfun);

				function downfun(e) {
					startx = e.clientX - canvasx;
					starty = e.clientY - canvasy;
					onoff = true;
				}

				canvas.addEventListener("mousemove", movefun);

				function movefun(e) {
					if(onoff == true) {
						endx = e.clientX - canvasx;
						endy = e.clientY - canvasy;
						cxt.beginPath()
						cxt.moveTo(startx, starty)
						cxt.lineTo(endx, endy)
						cxt.stroke()
						startx = endx
						starty = endy
					}
				}
								

				canvas.addEventListener("mouseup", upfun);

				function upfun() {
					onoff = false; //设置关闭画笔开关
				}
				
				document.getElementById("clear").addEventListener("click",clear);
				
				function clear() {
					cxt.clearRect(0,0,canvas.width,canvas.height)
				}
			}
		</script>
	</body>

</html>